<?php
$loader->requireOnce('ordo/Ticket.class.php');
/**
 * This class represents 'patient_bed' table.
 *
 * @package core.ordo
 * @author pktquynh
 * @version $Id:$
 * @copyright 2009 LHV Company
 */
class PatientBed extends ORDataObject {

    var $patient_bed_id = '';
    var $patient_id = '';
    var $bed_id = '';
    var $ticket_id = '';
    var $department_id = '';
    var $start_date = '';
    var $end_date = '';
    // $current = true, it means the patient_id is staying in bed_id currently.
    var $current = '';
    // original price of bed
    var $price = '';
    // bed price paid by insurance
    var $insurance_price = '';
    // bed price paid by patient
    var $paid_price = '';
    // type of bed price (hour/day)
    var $enum_price_type = '';

    var $_table         = 'patient_bed';
    var $_internalName  = 'PatientBed';
    var $_key       = 'patient_bed_id';

    public function PatientBed($id = 0)  {
        //call the parent constructor so we have a _db to work with
        parent::ORDataObject();
    }

    /**
     * Get information of current bed of the specific patient. Search table 'patient_bed' by criteria 'patient_id'
     * and 'current = true'.
     *
     * @param int $patientId The id of patient
     * @return false|array return false if the patient don't stay in any bed
     */
    public function getCurrentBedOfPatient($patientId) {
    	$field     =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');        

        $ds = new Datasource_sql();
        $sql = array (
            'cols'    => "p.name as patient_name, pa.patient_code as patient_code,
            			d.$field as department_name, r.$field as room_name, b.bed_id, b.code as bed_code",
            'from'    => $this->_table . " pb"
                         . " INNER JOIN person p ON pb.patient_id = p.person_id"
                         . " INNER JOIN patient pa ON p.person_id = pa.person_id"
                         . " INNER JOIN bed b ON pb.bed_id = b.bed_id "
                         . " INNER JOIN department d ON pb.department_id = d.department_id"
                         . " INNER JOIN room r ON r.room_id = b.room_id"                       
                         ,
            'where'   => "p.person_id = " . $patientId
                         . " AND pb.current = 1"
                         . " AND b.bed_id != 1"
                         . " AND b.deleted = 0",
            'orderby' => "code");

        $ds->setup($this->_db, $sql);
        $patientBeds = $ds->toArray();
        if (empty($patientBeds)) {
        	return false;
        } else {
        	return $patientBeds[0];
        }
    }

    /**
     * Change the current bed of patient from in_used status to unused status.
     * @param $patientId The id of patient
     * @param $deptId The id of department
     */
    public function changeBedStatus($patientId, $deptId) {
    	$sql = "UPDATE patient_bed SET current = 0, end_date = NOW() "
    	     . "WHERE patient_id = '$patientId' AND department_id = '$deptId' AND current = 1";
        $this->_execute($sql);
    }

    /**
     * Change a specific bed for some patient at department.
     * @param $patientId The id of patient
     * @param $deptId The id of department
     * @param $ticketId The id of ticket
     * @param $bed the bed object
     */
    public function changeBed($patientId, $deptId, $ticketId, $bed) {
    	$data = array ('patient_id'      => $patientId,
                       'bed_id'          => $bed->get('bed_id'),
    	               'ticket_id'       => $ticketId,
    	               'department_id'   => $deptId,
    	               'start_date'      => date("Y-m-d H:i:s"),
    	               'end_date'        => NULL,
    	               'current'         => 1,
                       'price'           => $bed->get('price'),
                       'insurance_price' => $bed->get('insurance_price'),
    	               'paid_price'      => ($bed->get('price') - $bed->get('insurance_price')),
                       'enum_price_type' => $bed->get('enum_price_type'));
        $this->populateArray($data);
        $result = $this->persist();
        return $this->patient_bed_id;
    }

    public function getBedByPatient($patientId) {
        $field      =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
        
        $status     =   Ticket::OPEN_STATUS;
        $dateFormat =   "%Y-%m-%d";

        $ds = new Datasource_sql();
        $sql = array (
            'cols'  =>  "d.$field as department_name, r.$field as room_name, b.bed_id, b.code as bed_code,
                        DATE_FORMAT(pb.start_date,'$dateFormat') start_date,
                        DATE_FORMAT(pb.end_date,'$dateFormat') end_date,
                        pb.price original_price, pb.insurance_price, pb.paid_price patient_price, pb.enum_price_type",
            'from'  =>  "$this->_table pb
                        INNER JOIN ticket tk  ON tk.ticket_id=pb.ticket_id
                        LEFT JOIN bed b ON pb.bed_id = b.bed_id
                        LEFT JOIN department d ON pb.department_id = d.department_id
                        LEFT JOIN room r ON r.room_id = b.room_id
                      ",
            'where' => "tk.patient_id=$patientId AND tk.status='$status'",
            'orderby' => "pb.start_date"
        );

        $ds->setup($this->_db, $sql);
        $res = $ds->toArray();
        if (count($res) > 0) {
        	foreach ($res as &$item) {
        		if (empty($item['end_date']) || $item['end_date']=="0000-00-00") {
                    $item['end_date']   =   'N/A';
                    $dayNumber  =   Utils::dateDiff(date('Y-m-d'), $item['start_date'])+1;
        		}
        		else {
                    $dayNumber  =   Utils::dateDiff($item['end_date'], $item['start_date'])+1;
                    $item['end_date']   =   L10nHelper::renderDateTime($item['end_date']);
        		}
        		$item['day_number']       =   $dayNumber;
        		$item['start_date']       =   L10nHelper::renderDateTime($item['start_date']);
        		$item['unit_price']       =   $item['original_price'];
        		$item['original_price']   =   $item['original_price'] * $dayNumber;
        		$item['insurance_price']  =   $item['insurance_price'] * $dayNumber;
        		$item['patient_price']    =   $item['patient_price'] * $dayNumber;
        	}
        }
        return $res;
    }
}
?>